/***************************************************************************
 * General Ledger, Copyright (C) 2008 Armin Moradi <feng.shaun@gmail.com>  *
 * http://fengshaun.wordpress.com                                          *
 *                                                                         *
 * This program is free software; you can redistribute it and/or modify    *
 * it under the terms of the GNU General Public License as published by    *
 * the Free Software Foundation; either version 3 of the License, or       *
 * (at your option) any later version.                                     *
 *                                                                         *
 * This program is distributed in the hope that it will be useful,         *
 * but WITHOUT ANY WARRANTY; without even the implied warranty of          *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the            *
 * GNU General Public License for more details.                            *
 *                                                                         *
 * You should have received a copy of the GNU General Public License       *
 * along with this program; if not, write to the Free Software             *
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 US  *
 ***************************************************************************/

#include <iostream>

#include <QMessageBox>

#include "client.h"

Client::Client(QObject *parent)
	: QTcpSocket(parent)
{
	connect(this, SIGNAL(connected()) , this, SLOT(initialize()));
}

Client::Client(QString host, quint16 port, QObject *parent)
	: QTcpSocket(parent)
{
	connectToHost(host, port);
	initialize();
}

Client::Client(QHostAddress host, quint16 port, QObject *parent)
	: QTcpSocket(parent)
{
	connectToHost(host, port);
	initialize();
}

void Client::initialize() {
	connect(this, SIGNAL(readyRead()), this, SLOT(read()));
// 	connect(this, SIGNAL(connected()), this, SLOT(reportConnected()));
	connect(this, SIGNAL(disconnected()), this, SLOT(deleteLater()));
	connect(this, SIGNAL(error(QAbstractSocket::SocketError)),
			this, SLOT(error(QAbstractSocket::SocketError)));
}

void Client::read() {
	m_blockSize = 0;
// 	std::cout << "Reading..." << std::endl;
	QDataStream in(this);
	in.setVersion(QDataStream::Qt_4_4);

	if (m_blockSize == 0) {
		if (bytesAvailable() <  sizeof(quint16)) {
// 			std::cout << "not enough bytes available" << std::endl;
			return;
		}
		in >> m_blockSize;
	}

	if (bytesAvailable() < m_blockSize) {
// 		std::cout << "not enough block bytes available" << std::endl;
		return;
	}

	m_data = 11;
	in >> m_data;

	if (!(in.status() == QDataStream::Ok)) {
		std::cout << "Error while reading data" << std::endl;
		return;
	}

	if (bytesAvailable() > 0) {
// 		std::cout << "more bytes available, reading again..." << std::endl;
		read();
		return;
	}

// 	std::cout << "reading complete!" << std::endl;
// 	std::cout << "read: " << int(m_blockSize) << " >> " << int(m_data) << std::endl;
	emit readDone(int(m_data));
}

void Client::send(int data) {
	m_data = quint8(data);
	
	QByteArray block;
	QDataStream out(&block, QIODevice::WriteOnly);
	out.setVersion(QDataStream::Qt_4_4);

	out << quint16(0) << m_data;
	out.device()->seek(0);
	out << quint16(block.size() - sizeof(quint16));

	write(block);
// 	std::cout << "sending " << int(m_data) << std::endl;
}

void Client::error(QAbstractSocket::SocketError err) {
	if (err == QAbstractSocket::RemoteHostClosedError) {
		QMessageBox::information(NULL, tr("Player left"),
								 tr("Remote player has left the game"),
								 QMessageBox::Ok);
	}
	std::cout << "Error: " << qPrintable(errorString()) << std::endl;
}

void Client::reportConnected() {
	std::cout << "Client is connected to "
			  << qPrintable(peerAddress().toString())
			  << " on port "
			  << int(peerPort())
			  << std::endl;
}
